package com.zx.oa.dao;


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {

    private static String driver;//����
    private static String url;//URL��ַ
    private static String user;//�û���
    private static String password;//����

    Connection conn=null;//�����������ݿ��
    PreparedStatement pstmt=null;//������SQL�����
    ResultSet rs=null;//���𷵻ؽ������

    static {
        //���þ�̬����飬������ص�ʱ�����ɳ�ʼ��
        init();
    }


    private static void init() {
        Properties pro=new Properties();
        InputStream is= BaseDao.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {

            pro.load(is);
            driver= pro.getProperty("driver");
            url= pro.getProperty("url");
            user= pro.getProperty("user");
            password= pro.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * ��ȡ���Ӷ���
     * @return
     */
    public Connection getConnection() {
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }




    /**
     * �ر���Դ����
     * @param conn
     * @param pstmt
     * @param rs
     */
    public void closeAll(Connection conn,PreparedStatement pstmt, ResultSet rs) {
        try {
            if (rs!=null) {
                rs.close();
            }
            if(pstmt!=null){
                pstmt.close();
            }
            if (conn!=null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * ��ɾ��ͨ�÷���
     * @param sql
     * @param params
     * @return
     */
    public int executeUpdateInfo(String sql,Object ... params) {
        int count=0;
        //��ȡ���Ӷ���
        conn=this.getConnection();
        try {
            pstmt=conn.prepareStatement(sql);
            for(int i=0;i<params.length;i++) {
                pstmt.setObject((i+1), params[i]);
            }
            count=pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.closeAll(conn, pstmt, rs);
        }
        return count;//������Ӱ������
    }

}
